import { fetchLogin, getInfo } from "@/api/user";
import router, { resetRouter } from "@/router";
import localCache from "@/utils/cache";

const getDefaultState = () => {
  return {
    token: "",
    name: "",
    avatar: "",
    loadedRouter: false,
    userInfo: {},
  };
};

const state = getDefaultState();

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState());
  },
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
  SET_RELOAD_ROUTER(state, loadedRouter) {
    state.loadedRouter = loadedRouter;
  },
  SET_USER_INFO(state, userInfo) {
    state.userInfo = userInfo;
  },
};

const actions = {
  // user login
  login({ commit, dispatch }, userInfo) {
    const { username, password } = userInfo;
    return new Promise((resolve, reject) => {
      fetchLogin({ username: username.trim(), password: password })
        .then(async (data) => {
          const { token } = data;
          commit("SET_TOKEN", token);

          localCache.setCache("token", data.token);
          //获取用户信息
          await dispatch("getInfo");
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // get user info
  getInfo({ commit }) {
    return new Promise((resolve, reject) => {
      getInfo()
        .then(async (response) => {
          const { data } = response;
          commit("SET_USER_INFO", data);
          localCache.setCache("userInfo", data);
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      commit("RESET_STATE");
      resolve();
    });
  },
  logout({ commit }) {
    return new Promise((resolve) => {
      router.push("/login");
      localCache.deleteCache("token");
      commit("RESET_STATE");
      commit("SET_USER_INFO", {});
      commit("tagsView/DELETE_ALL_VIEWS", null, { root: true });
      resetRouter();
      resolve();
    });
  },
  loadLocalLogin({ commit }) {
    const token = localCache.getCache("token");
    if (token) {
      commit("SET_TOKEN", token);
    }
    const userInfo = localCache.getCache("userInfo");
    if (userInfo) {
      commit("SET_USER_INFO", userInfo);
    }
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
